/****************************************************************************
**
** Copyright (C) 2013 Laszlo Papp <lpapp@kde.org>
** Contact: http://www.qt.io/licensing/
**
** This file is part of the QtSerialPort module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** As a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "serialportreader.h"

#include <QCoreApplication>
#include <iostream>
#include <QSettings>
#include <QFile>
#include <QTextStream>
#include "common.h"
#include <QDebug>
#include "utils.h"

QT_USE_NAMESPACE

namespace PCSG {

/*
SerialPortReader::SerialPortReader(QSerialPort *serialPort, QObject *parent)
    : QObject(parent)
    , m_serialPort(serialPort)
    , m_standardOutput(stdout)
{
    connect(m_serialPort, SIGNAL(readyRead()), SLOT(handleReadyRead()));
    connect(m_serialPort, SIGNAL(error(QSerialPort::SerialPortError)), SLOT(handleError(QSerialPort::SerialPortError)));
    connect(&m_timer, SIGNAL(timeout()), SLOT(handleTimeout()));

    m_timer.start(5000);
}*/

SerialPortReader::SerialPortReader(QObject *parent):QObject(parent),
    cnt_recv(0),
    time_interval_check(0),
    time_interval_send(0),
    time_interval_save(0),
    time_out_recv(0),
    time_last_save(0),
    time_last_recv(0),
    p_file_data(nullptr)
{
    //m_timer.setSingleShot(true);
    m_serialPort = new QSerialPort(this);

    connect(m_serialPort, SIGNAL(readyRead()), SLOT(SLOT_handleReadyRead()));
    connect(m_serialPort, SIGNAL(error(QSerialPort::SerialPortError)), SLOT(SLOT_handleError(QSerialPort::SerialPortError)));
    connect(&m_timer_sender, SIGNAL(timeout()), SLOT(SLOT_handleTimeout_sender()));
    connect(&m_timer_checker, SIGNAL(timeout()), SLOT(SLOT_handleTimeout_checker()));

    //connect(m_serialPort, SIGNAL(bytesWritten(qint64)), SLOT(handleBytesWritten(qint64)));
    //connect(m_serialPort, &QSerialPort::readyRead, SLOT_handleReadyRead);
    //connect(m_serialPort, &QSerialPort::error, SLOT_handleError);


}

SerialPortReader::~SerialPortReader()
{
    close();
}

bool SerialPortReader::init(
        const QString& folder_base,
        const QString& folder_settings_rel,
        const QString& folder_data_rel,
        const QString& folder_log_rel)
{
    ///
    /// deal with folder
    ///
    folder_settings = folder_base + folder_settings_rel;
    folder_data = folder_base + folder_data_rel;
    folder_log = folder_base + folder_log_rel;

    if(!Utils::checkFolder(folder_settings))
    {
        qout << "Create folder " << folder_settings << " failed" << endl;
        return false;
    }

    if(!Utils::checkFolder(folder_data))
    {
        qout << "Create folder " << folder_data << " failed" << endl;
        return false;
    }

    if(!Utils::checkFolder(folder_log))
    {
        qout << "Create folder " << folder_log << " failed" << endl;
        return false;
    }


    ///
    /// deal with files
    ///
    file_settings = "/serial_port.ini";
#ifdef ReadOnly_Top
    file_settings = folder_settings + "/serial_port_top.ini";
#endif
#ifdef ReadWrite_Bottom
    file_settings = folder_settings + "/serial_port_bottom.ini";
#endif


    QString time_str = Utils::getTimeStrByS();
    file_data = folder_data + "/" + time_str + ".txt";
#ifdef ReadOnly_Top
    file_data = folder_data + "/top_" + time_str + ".txt";
#endif
#ifdef ReadWrite_Bottom
    file_data = folder_data + "/bottom_" + time_str + ".txt";
#endif


    //p_file_data = fopen(file_data.toStdString().c_str(), "a");// ab
#ifdef ReadOnly_Top
<<<<<<< HEAD
    p_file_data = fopen(file_data.toStdString().c_str(), "ab+");// ab
=======
    p_file_data = fopen(file_data.toStdString().c_str(), "a");// ab
>>>>>>> 4977a0b4e4a2bfe4d482c40971685f086d97f3b7
#endif
#ifdef ReadWrite_Bottom
    p_file_data = fopen(file_data.toStdString().c_str(), "ab+");// ab
#endif

    if(p_file_data == nullptr)
    {
        qout << "Open file " << file_data << " failed" << endl;
        return false;
    }




    ///
    /// deal with setting file
    /// apply settings to serial port
    ///
    //    name = "COM1";
    //    baudRate = QSerialPort::Baud9600;
    //    dataBits = QSerialPort::Data8;
    //    parity = QSerialPort::NoParity;
    //    stopBits = QSerialPort::OneStop;
    //    flowControl = QSerialPort::NoFlowControl;
    QSettings ini_setting(file_settings, QSettings::IniFormat);
    QFile qfile_settings(file_settings);
    if(!qfile_settings.exists())
    {
        //ini_setting.beginGroup(("AboutSize"));
        ini_setting.setValue("serialport/name", settings.name);
        ini_setting.setValue("serialport/baudRate", settings.baudRate);
        ini_setting.setValue("app/time_interval_check", 5000);
        ini_setting.setValue("app/time_interval_send", 40);
        ini_setting.setValue("app/time_interval_save", 300000);// 5min
        ini_setting.setValue("app/time_out_recv", 5000);// 5s
    }
    settings.name = ini_setting.value("serialport/name").toString();
    settings.baudRate = ini_setting.value("serialport/baudRate").toInt();
    time_interval_check = ini_setting.value("app/time_interval_check").toInt();
    time_interval_send = ini_setting.value("app/time_interval_send").toInt();
    time_interval_save = ini_setting.value("app/time_interval_save").toInt();
    time_out_recv = ini_setting.value("app/time_out_recv").toInt();

    return true;
}

bool SerialPortReader::open()
{

    if (!m_serialPort->isOpen())
    {
        m_serialPort->setPortName(settings.name);
        m_serialPort->setBaudRate(settings.baudRate);
        m_serialPort->setDataBits(settings.dataBits);
        m_serialPort->setParity(settings.parity);
        m_serialPort->setStopBits(settings.stopBits);
        m_serialPort->setFlowControl(settings.flowControl);
        if (m_serialPort->open(QIODevice::ReadWrite))
        {
            qout << QString("Connected to %1 : %2")
                         .arg(settings.name)
                         .arg(settings.baudRate) << endl;
        }
        else
        {
            qout << QString("Failed connect to %1 : %2, info: %3")
                         .arg(settings.name)
                         .arg(settings.baudRate)
                         .arg(m_serialPort->errorString()) << endl;
            return false;
        }
    }


    m_timer_checker.start(time_interval_check);

#ifdef ReadWrite_Bottom
    m_timer_sender.start(time_interval_send);
#endif

    return true;
}

void SerialPortReader::close()
{
    if(m_serialPort != nullptr)
    {
        if(m_serialPort->isOpen())
        {
            m_serialPort->close();
        }
    }
    if(p_file_data != nullptr)
    {
        fclose(p_file_data);
    }
}

bool SerialPortReader::write(const QByteArray &writeData)
{
    QByteArray writeData_ =  writeData;
<<<<<<< HEAD
    writeData_ = writeData_.append('\r').append('\n');
    //writeData_ = writeData_.append('\n').append('\r');// device specific
    //writeData_ = writeData_.append('\r');// device specific
=======
    //writeData_ = writeData_.append('\r').append('\n');// device specific
>>>>>>> 4977a0b4e4a2bfe4d482c40971685f086d97f3b7
    qint64 bytesWritten = m_serialPort->write(writeData_);

    if (bytesWritten == -1)
    {
        qout << QObject::tr("Failed to write the data to port %1, error: %2")
                            .arg(m_serialPort->portName())
                            .arg(m_serialPort->errorString()) << endl;
        return false;
    }
    else if (bytesWritten != writeData_.size())
    {
        qout << QObject::tr("Failed to write all the data to port %1, error: %2")
                            .arg(m_serialPort->portName())
                            .arg(m_serialPort->errorString()) << endl;
        return false;
    }

    return true;
}

void SerialPortReader::SLOT_handleReadyRead()
{
    m_readData = m_serialPort->readAll();
    int64_t time_this = Utils::getSysTimeByMs();//%I64d, %lld
    time_last_recv = time_this;

#ifdef ReadOnly_Top
    int need_write_time_header = -1;
    for(int i = 0, len = m_readData.size(); i < len; i++)
    {
        if(m_readData.data()[i] != NULL)
        {
            need_write_time_header++;
            if(need_write_time_header == 0)
            {
                fprintf(p_file_data, "%I64d %d %c", time_this, i, m_readData.data()[i]);
            }
            else
            {
                fprintf(p_file_data, " %d %c", i, m_readData.data()[i]);
            }
        //#ifdef Disp
        if(EnableDisp)
        {
            qout << m_readData[i] << endl;
        }
        //#endif
        }
    }
    fprintf(p_file_data, "\n");

#endif

#ifdef ReadWrite_Bottom
//#ifdef Disp
    if(1)
    {
    qout << m_readData << endl;
    }
//#endif

    fprintf(p_file_data, "%I64d %s", time_this, m_readData.data());
    if(cnt_recv % 2 == 0)
    {
<<<<<<< HEAD
        //qout<<"bbb:"<<endl;
        //qout<<cnt_recv<<endl;
        //write("SR,01,001");
        //write("SR,02,001");

=======
        //qout<<"bbb:";
        //qout<<cnt_recv<<endl;
        write("SR,02,001");
>>>>>>> 4977a0b4e4a2bfe4d482c40971685f086d97f3b7
    }
    cnt_recv++;
#endif


}

/*
void SerialPortReader::SLOT_handleBytesWritten(qint64 bytes)
{
    if (bytes == len_send_msg)
    {
        qout << QObject::tr("Data successfully sent to port %1").arg(m_serialPort->portName()) << endl;
        //QCoreApplication::quit();
    }
    else
    {
        qout << QObject::tr("Data successfully sent to port %1").arg(m_serialPort->portName()) << endl;
    }
}*/


void SerialPortReader::SLOT_handleTimeout_sender()// only called in ReadWrite_top
{
    /*
    if (m_readData.isEmpty())
    {
        qout << QObject::tr("No data was currently available for reading from port %1").arg(m_serialPort->portName()) << endl;
    }
    else
    {
        qout << QObject::tr("Data successfully received from port %1").arg(m_serialPort->portName()) << endl;
        qout << m_readData << endl;
    }

    QCoreApplication::quit();*/
    //qout<<"aaa:";
    //qout<<cnt_recv<<endl;
<<<<<<< HEAD
    static int i = 0;
    if (i % 2 == 0)
    {
        write("SR,02,001");
    }
    else
    {
        write("SR,01,001");
    }
    i++;

=======
    write("SR,01,001");
>>>>>>> 4977a0b4e4a2bfe4d482c40971685f086d97f3b7
    //write("SR,02,001");
    //qDebug() << "write 2 msg";
}

void SerialPortReader::SLOT_handleTimeout_checker()
{
    int64_t time_this = Utils::getSysTimeByMs();//%I64d, %lld
    if(time_this - time_last_save > time_interval_save)
    {
        if( p_file_data != nullptr)
        {
            fclose(p_file_data);
            p_file_data = nullptr;
        }
        time_last_save = time_this;

        p_file_data = fopen(file_data.toStdString().c_str(), "ab+");// ab
        if(p_file_data == nullptr)
        {
            qout << "Open file " << file_data << " failed, app will exit" << endl;
            close();
            QCoreApplication::quit();
            return;
        }
    }
    if(time_this - time_last_recv > time_out_recv)
    {
        fprintf(p_file_data, "%I64d receive timeout\n", time_this);
        if( p_file_data != nullptr)
        {
            fclose(p_file_data);
            p_file_data = nullptr;
        }
        //time_last_recv = time_this;
        qout << "Msg recv time out > " << time_out_recv << endl;
        close();
        QCoreApplication::quit();
        return;
    }
}

void SerialPortReader::SLOT_handleError(QSerialPort::SerialPortError error)
{
    if (error == QSerialPort::ResourceError)
    {
        qout << "Serial port closed due to critical Error: "
                  << m_serialPort->errorString() << endl;
        close();
    }
    else if (error == QSerialPort::WriteError) {
        qout << QObject::tr("An I/O error occurred while writing the data to port %1, error: %2")
                .arg(m_serialPort->portName())
                .arg(m_serialPort->errorString()) << endl;
    }
}
}// namespace PCSG
